package com.tinxing.bp.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.ImmutableMap;
import com.tinxing.bp.base.service.BaseServiceImpl;
import com.tinxing.bp.commons.utils.enums.BizExceptionEnum;
import com.tinxing.bp.commons.utils.exception.ServiceException;
import com.tinxing.bp.modules.login.entity.vo.LoginBean;
import com.tinxing.bp.modules.user.dao.UserInfoDao;
import com.tinxing.bp.modules.user.entity.UserInfo;
import com.tinxing.bp.modules.user.service.IUserInfoService;
import com.tinxing.bp.security.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Automatic Generation
 * @since 2021-03-02
 */
@Service
public class UserInfoServiceImpl extends BaseServiceImpl<UserInfoDao, UserInfo> implements IUserInfoService {

        @Resource
        private AuthenticationManager authenticationManager;
        @Resource
        private JwtUtil jwtUtil;

        @Override
        public Map<String, String> authentication(LoginBean loginBean) {
                //通过账号密码构建令牌
                UserInfo userInfo = getOne(new QueryWrapper<UserInfo>().eq("account", loginBean.getAccount()));
                if (userInfo == null) {
                        throw new ServiceException(BizExceptionEnum.TOKEN_USEPWD_ERROR);
                }
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userInfo.getAccount(), loginBean.getPassword());
                //security通过UserDetails进行认证
                authenticationManager.authenticate(authenticationToken);
                //无异常,证明认证成功,创建令牌给前端
                String token = jwtUtil.createToken(userInfo.getAccount());
                return ImmutableMap.of("token", token);
        }
}